import React, { Component } from "react"
import { Descriptions, Tooltip, InputNumber, Modal, Switch } from 'antd';
import { QuestionCircleOutlined } from "@ant-design/icons";
import TheButton from '@/components/TheButton';
import { rechargeWithdrawList, rechargeWithdrawEdit, apiRiskConfigList, apiRiskConfigAddOrUpdate } from '@/request/wallet/rechargeWithdraw'
import EditInput from "./editInput";
import WalletRestrictions from "./allLimit";
import { limit } from "../enum"
// 入口文案label
let entryCopyLabel = (<div>
  <text style={{ marginRight: 10 }}>入口维护文案</text>
  <Tooltip placement="top" title={() => { return '入口关闭时展示维护文案' }}  >
    <QuestionCircleOutlined style={{ fontSize: '16px' }} />
  </Tooltip></div>)
// 入口开关label
let entrySwitchLabel = (<div>
  <text style={{ marginRight: 10 }}>入口开关</text>
  <Tooltip placement="top" title={() => { return '关闭时,APP点击充值会展示维护文案' }}  >
    <QuestionCircleOutlined style={{ fontSize: '16px' }} />
  </Tooltip></div>)
export default class Recharge extends Component {
  constructor() {
    super()
    this.ChildRef = React.createRef();
    this.state = {
      isNewPay: false,//
      newPaySwitch: false,//新人钱包充值限制开关
      newPayArr: [],//新人钱包充值限制数据
      imAmountConfigId: '',//业务id
      obj: {},
      limitationType: '', //其他充值配置参数
      otherCount: '', //其他次数
      otherMinute: '', //其他时间
      isOtherEdit: false,// 是否点击其他充值时的编辑，
      oldValue: '',//旧数据输入框
      switchLoading: false,//开关
      warning: false,
      otherMinuteWarning: false,//是否填写值修改颜色
      otherCountWarning: false,//是否填写值修改颜色
      otherMinuteOldValue: '',//其他配置项输入的值
      otherCountOldValue: '',//其他配置项输入的值
      editType: '',//提现充值类型
      title: "",
      arr: [],//弹窗的数据
    }
  }
  componentDidMount() {
    this.getData()
    this.getNewPay(limit["单日充值钱包额度"])
  }
  // 获取数据
  getData = async () => {
    let res = await rechargeWithdrawList({ type: 1 })
    if (res.code === 0 && res.data) {
      let data = res.data

      let limitationType = data.limitationType.split('-') // 其他充值配置项
      this.setState({
        newPaySwitch: data.newMemberRiskSwitch,
        obj: {
          minimumAmount: {
            label: '单次充值最低金额',
            key: 'minimumAmount',
            value: (data.minimumAmount / 100).toFixed(2),
            minValue: 0.01,
            maxValue: 999999.99,
            precision: 2,
            status: 0, //编辑 0 保存1
            bgColor: false
          },
          maximumAmount: {
            label: '单次充值最大金额',
            key: 'maximumAmount',
            value: (data.maximumAmount / 100).toFixed(2),
            minValue: 0.01,
            maxValue: 999999.99,
            precision: 2,
            status: 0, //编辑 0 保存1
            bgColor: false
          },
          dayAmount: {
            label: '单日充值总额度',
            key: 'dayAmount',
            value: (data.dayAmount / 100).toFixed(2),
            minValue: 0.01,
            maxValue: 999999.99,
            precision: 2,
            status: 0, //编辑 0 保存1
            bgColor: false
          },
          dayNumber: {
            label: '单日充值最大次数',
            key: 'dayNumber',
            value: data.dayNumber,
            minValue: 1,
            maxValue: 10000,
            precision: 0,
            status: 0, //编辑 0 保存1
            bgColor: false
          },
          timeout: {
            label: '超时未支付时间（秒）',
            key: 'timeout',
            value: data.timeout,
            minValue: 1,
            maxValue: 600,
            precision: 0,
            status: 0, //编辑 0 保存1
            bgColor: false
          },
          minutesNumber: {
            label: '1分钟内充值最大次数',
            key: 'minutesNumber',
            value: data.minutesNumber,
            minValue: 1,
            maxValue: 999,
            precision: 0,
            status: 0, //编辑 0 保存1
            bgColor: false
          },
          hourNumber: {
            label: '1天内充值最大次数',
            key: 'hourNumber',
            value: data.hourNumber,
            minValue: 1,
            maxValue: 999,
            precision: 0,
            status: 0, //编辑 0 保存1
            bgColor: false
          },
          text: {
            label: entryCopyLabel,
            key: 'text',
            value: data.text,
            status: 0, //编辑 0 保存1
            bgColor: false,
            precision: 0,
          },
          entrySwitch: {
            label: entrySwitchLabel,
            key: 'entrySwitch',
            value: data.entrySwitch === 0 ? true : false,
            status: 0, //编辑 0 保存1
          },
          realnameOrNot: {
            label: '是否需要实名',
            key: 'realnameOrNot',
            value: data.realnameOrNot === 0 ? true : false,
            status: 0, //编辑 0 保存1
          },
        },
        otherCount: limitationType[1],
        otherMinute: limitationType[0],
        imAmountConfigId: data.imAmountConfigId,
        otherCountOldValue: limitationType[1],
        otherMinuteOldValue: limitationType[0],
        editType: 1
      })
    }
  };
  //获取新人钱包充值限制数据
  getNewPay = async (configType) => {
    let res = await apiRiskConfigList({ configType })
    if (res.code === 0 && res.data) {
      this.setState({
        newPayArr: res.data.list.map(item=>{
          return {
            ...item,
            amountPerDay: React.$transNum(item.amountPerDay, 0, -2)
          }
        })
      })
    }
  }

  // 编辑 
  edit = (data) => {
    let { obj, otherMinuteOldValue, otherCountOldValue, oldValue } = this.state
    Object.values(obj).map((v, i) => {
      if (data.index === i) {
        oldValue = v.value
        return v.status = 1
      } else {
        this.state.isOtherEdit = false
        return v.status = 0
      }
    })
    this.setState({
      obj,
      oldValue,
      warning: false,
      otherCount: otherCountOldValue,
      otherMinute: otherMinuteOldValue
    })
  }
  // 取消
  cancel = (data) => {
    let { obj } = this.state
    Object.values(obj).map((v, i) => {
      if (data.index === i) {
        v.status = 0
        return v
      }

    })
    this.setState({
      obj,
      warning: false
    })
  }


  // 保存时掉接口
  saveFn = async (params, v) => {
    let res = await rechargeWithdrawEdit({
      imAmountConfigId: this.state.imAmountConfigId, [v.key]: v.precision === 0 ? params.data.value : React.$transNum(params.data.value, 0, 2)
    })
    if (res.code === 0) {
      v.status = 0
      v.value = params.data.value
      React.$message({ type: 'success', content: '保存成功' })
      this.getData()
      return v
    }
  }
  // 保存
  save = (params) => {
    let { obj } = this.state
    let numValues = Number(params.data.value)
    Object.values(obj).map(async (v, i) => {
      if (params.index === i) {
        if (params.data.key === 'minimumAmount' && numValues >= Number(obj.maximumAmount.value)) {
          Modal.error({
            content: '单次最低金额不能大于或等于单次最高金额',
            okText: '确定'
          });
          return false
        }
        if (params.data.key === 'maximumAmount') {
          if (numValues <= Number(obj.minimumAmount.value)) {
            Modal.error({
              content: '单次最高金额不能小于或等于单次最低金额',
              okText: '确定'
            });
          } else if (numValues > Number(obj.dayAmount.value)) {
            Modal.error({
              content: '单次充值最高金额不能大于单日充值总额度',
              okText: '确定'
            });
          } else {
            this.saveFn(params, v)
          }
          return false
        }
        if (params.data.key === 'dayAmount' && numValues < Number(obj.maximumAmount.value)) {
          Modal.error({
            content: '单日充值总额度不能小于单次充值最高金额',
            okText: '确定'
          });
          return false
        }
        this.saveFn(params, v)
      }
    })
  }
  // 开关设置
  switchChange = (e, params, index) => {
    let { obj } = this.state
    let entrySwitchContent = params.value ? '关闭后，用户将不能进入充值页' : '开启后，用户可进入充值页'
    let realnameOrNotContent = params.value ? '关闭后，用户充值无需实名认证' : '开启后，用户充值需实名认证'
    Object.values(obj).map(async (v, i) => {
      let _this = this
      if (index === i) {
        Modal.confirm({
          title: '提示',
          content: v.key === 'entrySwitch' ? entrySwitchContent : realnameOrNotContent,
          okText: '确认',
          cancelText: '取消',
          async onOk() {
            let res = await rechargeWithdrawEdit({
              imAmountConfigId: _this.state.imAmountConfigId, [v.key]: e ? 0 : 1
            })
            if (res.code === 0) {
              React.$message({ type: 'success', content: v.value ? '关闭成功' : '开启成功' })
              _this.getData()
            }
          },
        });
        this.setState({ obj })
      }
    })
  }
  //其他充值配置编辑
  editOtherRecharge = () => {
    let { obj, otherMinuteOldValue, otherCountOldValue, oldValue } = this.state
    Object.values(obj).map((v) => {
      oldValue = v.value
      return v.status = 0
    })
    this.setState({
      isOtherEdit: true,
      oldValue,
      otherCount: otherCountOldValue,
      otherMinute: otherMinuteOldValue
    })
  }
  // 取消编辑其他配置 
  cancelOtherRecharge = () => {
    let { otherMinuteOldValue, otherCountOldValue } = this.state
    this.setState({
      isOtherEdit: false,
      otherCount: otherCountOldValue,
      otherMinute: otherMinuteOldValue
    })

  }
  // 保存编辑其他配置 
  saveOtherRecharge = async () => {
    let { otherCount, otherMinute, imAmountConfigId } = this.state
    let regex = /^(?!.*(?<![\d.])0\d).*$/ //不能以.结尾 并且除小数点外不能连续输入0
    if (!regex.test(otherMinute) || !regex.test(otherCount)) {
      React.$message({ type: 'error', content: '输入格式不正确!' })
      return false
    }
    if (otherMinute === '' && otherCount === '') {
      this.setState({ otherMinuteWarning: true, otherCountWarning: true })
      React.$message({ type: 'error', content: '此项为必填项！' })
      return false
    }
    if (otherMinute === '') {
      this.setState({ otherMinuteWarning: true })
      React.$message({ type: 'error', content: '此项为必填项！' })
      return false
    }
    if (otherCount === '') {
      this.setState({ otherCountWarning: true })
      React.$message({ type: 'error', content: '此项为必填项！' })
      return false
    }
    if (otherMinute < 1 || otherMinute > 60) {
      React.$message({ type: 'error', content: '只能输入1-60的数字' })
      return false
    }
    if (otherCount < 1 || otherCount > 1000) {
      React.$message({ type: 'error', content: '只能输入1-1000的数字' })
      return false
    }
    let params = {
      imAmountConfigId: imAmountConfigId,
      limitationType: otherMinute + '-' + otherCount
    }

    let res = await rechargeWithdrawEdit({
      ...params
    })
    if (res.code === 0) {
      React.$message({ type: 'success', content: '保存成功' })
      this.getData()
      this.setState({
        isOtherEdit: false,
      })
    }
  }
  //其他配置中次数值改变
  otherCountChange = (e) => {
    let value = e.target.value
    if (value !== '') {
      this.setState({
        otherCountWarning: false
      })
    }
    value = value.replace(/[^\d]/g, '')// 只能是数字
    this.setState({
      otherCount: value,
    })
  }
  //其他配置中时间值改变
  otherMinuteChange = (e) => {
    let value = e.target.value
    if (value !== '') {
      this.setState({
        otherMinuteWarning: false
      })
    }
    value = value.replace(/[^\d]/g, '')// 只能是数字
    this.setState({
      otherMinute: value,
    })

  }
  //点编辑打开弹窗
  showModalNewPay = () => {
    this.setState({
      isShow: false
    }, () => {
      this.setState({
        title: "单日充值钱包额度",
        arr: this.state.newPayArr,
        isShow: true
      }, () => {
        this.ChildRef.current.control(true)
      })
    })
  }
  //保存弹窗后更新数据
  saveModal = async (params) => {
    const { title } = this.state
    let current = limit[title]
    const newVal = params.map(item => {
      delete item.id
      return {
        configType: current,
        ...item,
        amountPerDay: React.$transNum(item.amountPerDay, 0, 2)
      }
    })
    let res = await apiRiskConfigAddOrUpdate(newVal)
    if (res.code === 0) {
      this.getNewPay(current)
      this.ChildRef.current.control(false)
      React.$message({ type: 'success', content: '保存成功' })
    }
  }

  //新人钱包充值限制开关
  newPay = async (flag) => {
    if (flag && this.state.newPayArr.length == 0) {
      //0条打开编辑弹窗
      this.showModalNewPay()
      return
    } else {
      let res = await rechargeWithdrawEdit({
        imAmountConfigId: this.state.imAmountConfigId,
        newMemberRiskSwitch: ~~flag
      })
      if (res.code === 0) {
        React.$message({ type: 'success', content: '保存成功' })
        this.getData()
        this.setState({
          newPaySwitch: flag
        })
      }
    }
  }

  render() {
    const { isShow, newPaySwitch, newPayArr, obj, otherMinute, otherCount, isOtherEdit, switchLoading, otherMinuteWarning, otherCountWarning, editType, title, arr } = this.state
    let style = { display: 'flex', justifyContent: 'center', alignItems: 'center' }
    return (
      <div >
        <div style={{ fontWeight: 'bold', marginBottom: 20, fontSize: 16 }}>钱包充值配置</div>
        <Descriptions layout="vertical" bordered column={10} size='small' labelStyle={style} style={{ width: 1650 }}>
          {
            Object.values(obj).map((item, index) => {
              return (
                <Descriptions.Item label={item.label} style={{ textAlign: (item.key === 'realnameOrNot' || item.key === 'entrySwitch') && 'center' }}>
                  {
                    item.key === 'realnameOrNot' || item.key === 'entrySwitch' ?
                      <Switch style={{ margin: 'auto' }} checked={item.value} onChange={(e) => this.switchChange(e, item, index)} loading={switchLoading} />
                      : <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
                        <EditInput editType={editType} editData={item} editIdex={index} onEdit={this.edit} onSave={this.save} onCancel={this.cancel} />
                      </div>
                  }
                </Descriptions.Item>
              )
            })
          }
        </Descriptions>
        <div style={{ margin: '20px 0' }}>其他充值配置</div>
        {isOtherEdit ? <div>
          <input style={{ border: otherMinuteWarning ? '1px solid red' : '1px solid #ccc', width: 80, paddingLeft: 5 }} onInput={this.otherMinuteChange} value={otherMinute} />
          分钟内，支付失败次数超过<input style={{ border: otherCountWarning ? '1px solid red' : '1px solid #ccc', width: 80, paddingLeft: 5 }} onInput={this.otherCountChange} value={otherCount} />次时，限制用户充值
          <TheButton haspermi={["wallet:rechargeWithdraw:cancel"]} onClick={() => this.cancelOtherRecharge()}>取消</TheButton>
          <TheButton haspermi={["wallet:rechargeWithdraw:save"]} onClick={() => this.saveOtherRecharge()}>保存</TheButton>
        </div> : <div> <text>【{otherMinute}】分钟内，支付失败次数超过【{otherCount}】次时，限制用户充值</text><TheButton haspermi={["wallet:rechargeWithdraw:edit"]} onClick={this.editOtherRecharge}>编辑</TheButton></div>}
        <div style={{ marginTop: '20px' }}>
          <span style={{ marginRight: '20px' }}>新人钱包充值限制</span>
          <Switch checked={newPaySwitch} onChange={this.newPay} />
        </div>
        <div style={{ marginTop: '20px' }}>
          {
            newPayArr.map(item => {
              return <div>
                新人注册第【{item.startDay}-{item.endDay}】天，单日充值额度为【{item.amountPerDay}】元，超出后提示文案为【{item.noticeMessage}】
              </div>
            })
          }
        </div>
        <div style={{ marginTop: '20px' }}>
          <TheButton style={{ marginLeft: '300px' }} type="primary" onClick={this.showModalNewPay}>编辑</TheButton>
        </div>
        {isShow && <WalletRestrictions ref={this.ChildRef} title={title} arr={arr} save={this.saveModal} tips="编辑新人充值钱包限制" />}
      </div>
    )
  }
}